package sealte.port.scanner.core;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.TreeSet;

import sealte.port.scanner.frame.MainFrame;

public class PortScanner {
	private TreeSet<Integer> data = null;
	private int port1 = 0;
	private int port2 = 0;
	private int maxThread = 0;
	private InetAddress hostAddress = null;
	private long startTime;
	private MainFrame mf = null;
	private String ip = null;
	
	public PortScanner(MainFrame mf,String ip,int port1_int,int port2_int,int maxThread_int){
		this.ip = ip;
		this.port1 = port1_int - 1;
		this.port2 = port2_int;
		this.maxThread = maxThread_int;
		try {
			this.hostAddress = InetAddress.getByName(ip);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		this.data = new TreeSet<Integer>();
		this.mf = mf;
		this.startTime = System.currentTimeMillis();
	}
	
	public void startScan(){
		mf.getJta_content().append("Start...\n");
		for(int i=0;i<maxThread;i++){
			startThread();
		}
	}
	
	private void startThread(){
		Thread t = new Thread(new Runnable(){
			public void run(){
				int port;
				while((port=getIport())<=port2){
					try{
						mf.getJta_content().append("Scanning "+ip+": "+port+"\n");
						Socket socket = new Socket(hostAddress,port);
						mf.getJta_content().append(ip+": "+port+" ---------Open!-------\n");
						data.add(port);
						socket.close();
					}catch(IOException e){}
					if(port==port2){
						String portList = "Total:";
						int flag = 0;
						for(int i:data){
							portList += i;
							flag++;
							if(flag<data.size()){
								portList += "-";
							}
						}
						portList += "\n Cost time: " + (System.currentTimeMillis() - startTime)/(1000*60) + " mins";
						mf.getJta_content().append(portList);
					}
				}
			}
		});
		t.start();
	}
	
	private synchronized int getIport(){
		int newPort1 = ++port1;
		if(newPort1%100==0){
			mf.getJta_content().setText("");
		}
		return newPort1;
	}
}
